<template>
  <div>
    <el-row>
      <el-col>
        <my-form
          :formOptions="findFormOptions"
          :isInline="true"
          :isSearch="true"
          @sureSubmit="findTableData"
        >
          <template #bottom_button>
            <el-button
              icon="el-icon-refresh"
              size="mini"
              type="primary"
              @click="reset"
              >重置</el-button
            >
          </template>
        </my-form>
      </el-col>
    </el-row>
    <el-row type="flex" justify="end">
      <el-col :span="2">
        <!-- nowRoot从myInfo里面取，加判断 -->
        <el-button size="mini" @click="add" icon="el-icon-circle-plus" type="primary" v-if="nowRoot==='校管理员'"
          >新增</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <my-table
          :hasBorder="true"
          :hasIndex="true"
          :hasPagination="true"
          :hasStripe="true"
          :hasSelection="false"
          :tableColumnOptions="tableColumnOptions"
          :tableData="tableData"
        >
        <template #subCategory="{data}">
          {{ xueke[data.subCategory ]}}
        </template>
          <template #operation="{ data }">
            <el-button type="text" @click="update(data)">编辑</el-button>
            <el-button type="text" @click="remove(data)">删除</el-button>
          </template>
        </my-table>
      </el-col>
    </el-row>
    <my-dialog :dialogVisible.sync="infoDialog" :title="infoTitle">
      <template #content>
        <my-form
          style="max-width:600px"
          :form="isAddInfo ? copyForm : form"
          :formOptions="infoFormOptions"
          
          :rules="infoRules"
          @sureSubmit="infoFormSubmit"
          ref="infoForm"
        >
          <template #subUserid="{ data }">
            <el-autocomplete
              v-model="test1"
              :fetch-suggestions="querySearch"
              placeholder="请选择负责人"
              @select="handleSelect_person"
            ></el-autocomplete>
          </template>
        </my-form>
      </template>
    </my-dialog>
  </div>
</template>

<script>
import request from "@/utils/request"
import myForm from "@/components/myForm.vue";
import myTable from "@/components/myTable.vue";
import myDialog from "@/components/myDialog.vue";
import {projectCate,getModelByLabel,getLabelByModel} from "@/utils/metaInfo"
import {
  A_tableData,
  A_add,
  A_update,
  A_remove,
  A_getUtil,
  A_changeUtil,
} from "@/api/infoMange/subjectInformation";
import { A_getUserList } from "@/utils/aboutUsers";
import cloneDeep from "lodash/cloneDeep";
import { mapState } from 'vuex';
export default {
  name: "subjectInformation",
  inject: ["reload"],
  data() {
    return {
      findFormOptions: [{ type: "input", label: "学科名称", model: "subName" }],
      tableColumnOptions: [
        {
          label: "学科名称",
          prop: "subName",
          width: "150",
        },
                {
          label: "单位名称",
          prop: "subUtils",
          width: "250",
        },
                {
          label: "负责人姓名",
          prop: "name",
          width: "150",
        },
                {
          label: "学科负责人",
          prop: "subUserid",
          width: "150",
        },
        {
          label: "学科代码",
          prop: "subId",
          width: "150",
        },


        {
          label: "学科门类",
          isSlot:true,
          slotName:'subCategory',
          prop: "subCategory",
          width: "150",
        },
        // {
        //   label: "单位号",
        //   prop: "subUtils",
        //   width: "150",
        // },

        {
          label: "操作",
          width: "180",
          isSlot: true,
          slotName: "operation",
          fixed: "right",
        },
      ],
      tableData: [],
      infoDialog: false,
      infoTitle: "编辑操作",
      isAddInfo: false,
      form: {},
      copyForm: {},
      nowDropItem: "",
      infoFormOptions: [
        {
          type: "input",
          label: "学 科 名 称",
          model: "subName",
        },
        {
          type: "input",
          label: "学科代码",
          model: "subId",
        },
        {
          type: "slot",
          slotName: "subUserid",
          label: "学科负责人",
          model: "subUserid",
        },
        {
          type: "select",
          label: "科研单位名称",
          model: "subUtils",
          options:[]
        },
        {
          type: "radio",
          label: "学科门类",
          model: "subCategory",
          options:projectCate
        },
        
      ],
      infoRules: {
        subName: [{ required: true, message: "请输入学科名称" }],
        subId: [{ required: true, message: "请输入学科号码" }],
        // subUserid: [{ required: true, message: "请输入学科负责人" }],
        subCategory: [{ required: true, message: "请选择学科分类" }],
        subUtils: [{ required: true, message: "请选择科研单位" }],
      },
      test1: "",
      xueke:['自然科学','人文社科'],
      user_list: null,
    };
  },
  components: {
    myForm,
    myTable,
    myDialog,
  },
  created() {
    this.getTableData();
    this.getSciUtils()
  },
  methods: {
    async getSciUtils(){
      let sciUtils = await request({
        url:"/UserManage/showIdeentity",
        method:"get"
      })
      let arr = [];
      sciUtils.data.sciUtils.forEach((item) => {
        let { utilsName, utilsKey } = item;
        arr.push({ label: utilsName, model: utilsKey });
      });
      console.log(arr)
      this.infoFormOptions.map((item) => {
      if (item.model) {
        if (item.label === "科研单位名称") {
          item.options =arr;
        }
      }
      })
      // console.log(sciUtils.data)
    },
    async getUserList() {
      let result = await A_getUserList();
      result.forEach((item) => {
        const value = item.userId + " : " + item.userName;
        item.value = value;
      });
      this.user_list = result;
    },
    async findTableData(data) {
      let result = await A_tableData(data);
      if (result.code === 1) {
        this.tableData = cloneDeep(result.data);
      } else {
        this.$message({ type: "error", message: "信息获取失败" });
      }
    },
    async getTableData() {
      let result = await A_tableData({});
      if (result.code === 1) {
        this.tableData = cloneDeep(result.data);
        this.tableData.forEach(item=>{
          item.subCategory = this.getLabelByModel(item.subCategory,projectCate)
        })
        console.log(tableData)
      } else {
        this.$message({ type: "error", message: "信息获取失败" });
      }
    },
    async reset() {
      let result = await A_tableData({});
      if (result.code === 1) {
        this.tableData = cloneDeep(result.data);
      } else {
        this.$message({ type: "error", message: "信息获取失败" });
      }
    },
    add() {
      this.isAddInfo = true;
      this.infoDialog = true;
      this.getUserList();
    },
    update(data) {
      this.isAddInfo = false;
      this.infoDialog = true;
      this.form = cloneDeep(data);
      this.getUserList();
    },
    remove(data) {
      this.$confirm("你确定要删除该信息吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { subKey } = data;
          let res = await A_remove(subKey);
          if (res.code === 1) {
            this.$message({ type: "success", message: res.data });
            this.reload();
          } else {
            this.$message({ type: "error", message: res.msg });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async infoFormSubmit(data) {
      console.log(data)
      data.subCategory = getModelByLabel(data.subCategory,projectCate)
      if (this.isAddInfo) {
        let res = await A_add(data);
        if (res.code === 1) {
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      } else {
        let res = await A_update(data);
        if (res.code === 1) {
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      }
      // this.$refs.filesUpload.submit();
    },
    async getUtil() {
      let result = await A_getUtil();
      this.nowDropItem = result;
    },
    async handleCommand(command) {
      let result = await A_changeUtil(command);
      if (result.code === 1) {
        this.$message({ type: "success", message: `当前部门为${command}` });
        this.reload();
      } else {
        this.$message({ type: "error", message: "切换失败" });
      }
    },
    querySearch(queryString, cb) {
      var user_list = this.user_list;
      var results = queryString
        ? user_list.filter(this.createFilter(queryString))
        : user_list;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (user_list) => {
        return (
          user_list.userName.indexOf(queryString) === 0
        );
      };
    },
    handleSelect_person(item) {
        
      this.$refs.infoForm.form.subUserid = item.userId;
    },
  },
  computed: {
    ...mapState('myInfo',['nowRoot'])
  },
};
</script>

<style scoped>
.upload-demo {
  display: inline-block;
  margin: 0 3px;
}
</style>